package com.guo.mixframe.framework.receivers.websocket

import com.guo.mixframe.framework.receivers.GameMessageHelper
import com.guo.mixframe.framework.receivers.websocket.WebSocketClient
import io.netty.buffer.ByteBuf
import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServer
import io.vertx.core.http.HttpServerOptions
import io.vertx.core.http.WebSocket
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @author  gx
 * @description
 */
class WebSocketServer(
  private val port: Int,
  private val timeOut: Int,
  private val netMessageHelper: GameMessageHelper
) : AbstractVerticle() {


  override fun start() {
    val httpServerOption = HttpServerOptions().setIdleTimeout(timeOut)
    val server = vertx.createHttpServer(httpServerOption)
    server.webSocketHandler { ws ->
      val client = WebSocketClient(ws)
      ws.handler {
        handleReceive(it.byteBuf, client)
      }

    }
    server.listen(port)
  }

  private fun handleReceive(byteBuf: ByteBuf?, client: WebSocketClient) {
    GlobalScope.launch(vertx.dispatcher()) {
      //buffer是RoutingContext创建的，不需要释放
      netMessageHelper.handleReceive(byteBuf, client)
    }
  }


  override fun stop() {
    super.stop()
  }
}
